# -*- coding: utf-8 -*-
#  通常数据工厂，获取各种model,从数据库获取常用的数据列表
# @Time    ： 2021/11/30  19:55
# @Auther  ： 徐良
# File     :  modelFactory.py

from PySide6.QtSql import QSqlQueryModel, QSqlQuery
from share.dbService import DB_Sqlite, DB_MySql


class DataFactory(object):
    """
    数据库工厂
    """
    def __init__(self):
        pass

    # 根据sql语句返回 model(QSqlQueryModel)
    @staticmethod
    def getQueryModelForSql(sStr, baseDbType=None):
        if baseDbType is None:
            # db = BIO_DB
            return None

        elif baseDbType == 'mysql':

            return None

        elif baseDbType == 'sqlite':
            db = DB_Sqlite

        # 创建 QSqlQuery 对象并与数据库连接相关联
        query = QSqlQuery(db)

        # 使用 QSqlQuery 对象调用 exec 方法执行 SQL 查询
        query.exec(sStr)

        # 创建 QSqlQueryModel 对象
        model = QSqlQueryModel()

        # 将 QSqlQuery 对象设置为模型的查询
        model.setQuery(query)

        return model


    # 获取菜单列表
    @staticmethod
    def getMenuList(actionNum, sType=None):

        num = actionNum[0:5] + '.'
        sql = """
        SELECT e.fnumber, e.fname, e.fid, e.fparentid, e.flevel, e.fdetail 
        FROM t_menu e LEFT JOIN t_menu m ON e.fparentid = m.fid 
        where substr(e.fnumber, 1, 6) = '{sn}' ORDER BY e.fnumber
        """
        sql = sql.format(sn=num)

        if sType is None:
            sType = 'mysql'
        model = DataFactory.getQueryModelForSql(sql, sType)
        return model


    # 获取工具栏action 列表
    @staticmethod
    def getActionList(sStr, sType=None):
        sql = """select fnumber,fname,fobjectname,fqicon,ftooltip,fenable,fvisible,fbrowseVisible,feditVisible 
        from t_action where substr(fnumber,1,5) = '{num}'
        and fobjectname <> 'N' and Fvisible= 1 order by fnumber""".format(num=sStr)

        if sType is None:
            sType = 'mysql'
        model = DataFactory.getQueryModelForSql(sql, sType)
        return model

        # 获取工具栏浏览界面命令列表

    @staticmethod
    def getBrowseActionList(fnum, sType=None):
        """
        获取工具栏浏览界面命令列表
        :param fnum: 菜单编码
        :return:
        """
        sql = "select Fname from t_action where fnumber='{num}'".format(num=fnum)

        if sType is None:
            sType = 'mysql'
        model = DataFactory.getQueryModelForSql(sql, sType)

        # sDic = eval(model.record(0).value('FMenusAndActions'))
        # browseList = sDic['browseAction'].split(',')
        # return browseList

    # 获取工具栏编辑界面命令列表
    @staticmethod
    def getEditActionList(fnum, sType=None):
        """
        获取工具栏编辑界面命令列表
        :param fnum: 菜单编码
        :return:
        """
        sql = "select FMenusAndActions from t_action where fnumber='{num}'".format(num=fnum)

        if sType is None:
            sType = 'mysql'
        model = DataFactory.getQueryModelForSql(sql, sType)

        # sDic = eval(model.record(0).value('FMenusAndActions'))
        # editList = sDic['editAction'].split(',')
        # return editList
        return []


class SqlForSave(object):
    def __init__(self, insertList=None, updateList=None, delList=None):
        super(SqlForSave, self).__init__()
        self.insertList = insertList
        self.updateList = updateList
        self.delList = delList


    @staticmethod
    def execSqlList(sqllist, sDbtype=None):
        try:
            if sDbtype is None:
                db = DB_MySql
            elif sDbtype == 'sqlite':
                db = DB_Sqlite

            query = QSqlQuery(db)
            query.exec_('BEGIN TRANSACTION;')  # 开始事务
            for o in sqllist:
                try:
                    query.exec_(o)
                except Exception as e:
                    print("执行失败：", e)
                    query.exec_('ROLLBACK;')  # 回滚事务
                    return {'ret': False, 'info': str(e)}

            query.exec_('COMMIT;')  # 提交事务
            return {'ret': True}

        except Exception as e:
            # 捕获并处理异常
            return {'ret': False, 'info': str(e)}